import api from '../api/api.js';
import os from '../os.js';

/**
 * 插屏广告
 */
export class InterstitialAd {
  // 广告
  ad = null;
  // 广告id
  adUnitId = '';
  // 当前广告配置
  currenAdconf = null;
  // 当前索引
  currentIndex = 0;
  // 是否加载显示
  isLoadSucces = false;
  // 是否有数据
  isHasData = false;
  // 是否可展示广告
  isCanShow = true;

  // 传入配置
  options = {
    // 广告配置列表
    adConfList: false,
    // 配置变化时触发
    onAdConfChange: null,
    // 加载成功触发
    onLoad: null,
    // 关闭广告触发
    onClose: null,
    // 广告出错触发
    onError: null,
    // 广告显示触发
    onShow: null
  };

  constructor(options) {

    Object.assign(this.options, options);

    if (!this.options.onAdConfChange) {
      throw new Error('options.onAdConfChange is required');
    }

    if (!this.options.onLoad) {
      throw new Error('options.onLoad is required');
    }

    if (!this.options.onClose) {
      throw new Error('options.onClose is required');
    }

    if (!this.options.onError) {
      throw new Error('options.onError is required');
    }

    if (!this.options.onShow) {
      throw new Error('options.onShow is required');
    }

    if (this.options.adConfList === false) {
      this.getAdvertConfig()
      return;
    }

    this._changeCurrentAdConf(this.currentIndex);

    this._init();
  }

  async _init() {
    if (this.adUnitId === '') {
      this.options.onError({errCode: 158802, errMsg: "The adUnitId is invalid"});
      return;
    }

    // 创建广告
    console.info('adUnitId', this.adUnitId);
    this.ad = os.createInterstitialAd({
      adUnitId: this.adUnitId
    });
  
    this.options.onLoad({type: 'reg'});

    // 绑定事件
    this.unBindAdListener();
    this.bindAdListener();

    // 加载广告
    this.ad.load() 
      .then(() => {
        this.isLoadSucces = true;
        this.showAd();
      })
      .catch((err) => {
        this.isLoadSucces = false;
      });
  }

  async showAd() {
    if (this.ad) {
      await this.ad.show().then(() => {
        console.log('Ad show succes:', '广告显示成功');
        this.options.onShow();
      }).catch((err) => {
        // console.log('Ad show error:', err);
        // this.options.onError(err);
      });
    }
  }

  show(){
    if (!this.isHasData || !this.isCanShow) {
      return;
    }

    if(this.isLoadSucces === false){
      this.currentIndex += 1;
      this._changeCurrentAdConf(this.currentIndex);
      this._init();
      return;
    }
    
    this.showAd();
  }

  bindAdListener(){
    const _this = this;

    this.ad.onLoad(() => {
      _this.isLoadSucces = true;
      _this.options.onLoad({type: 'success'});
    });

    this.ad.onClose(() => {
      _this.isCanShow = false;
      setTimeout(function(){
        _this.isCanShow = true;
      }, 60000);
      _this.options.onClose();
    });
    
    this.ad.onError(err => {
      console.warn('Ad error:', err);
      _this.options.onError(err);
    });
  }

  unBindAdListener(){
    if(this.ad === null){
      return;
    }

    this.ad.offLoad(() => {
      console.info("解除绑定 load 事件的监听器");
    });

    this.ad.offError(() => {
      console.info("解除绑定 error 事件的监听器");
    });

    this.ad.offClose(() => {
      console.info("解除绑定 close 事件的监听器");
    });
  }

  destroy(){
    if(this.ad === null){
      return;
    }

    this.unBindAdListener();
    this.ad.destroy().then(() => {
      console.info('Ad destroy: 销毁成功');
    }).catch((err) => {
      console.warn('Ad destroy:', err);
    });
    this.ad = null;
  }

  getAdvertConfig() {
    api.getAdvertConfig(2, {showErr: false}).then(res => {
      if (res.code == 200) {
        const strategy = res.data?.advert_strategy || [];
        if (strategy.length > 0) {
          this.options.onAdConfChange({type: 1, data: res.data});
          this.options.adConfList = res.data;
          this.isHasData = true;
          this._changeCurrentAdConf(this.currentIndex);
          this._init();
          return;
        }
      }
      this.isHasData = false;
      this.options.onError({errCode: -1, errMsg: "No advertising configuration"});
    }).catch(err => {
      this.options.onError({errCode: -1, errMsg: "No advertising configuration"});
    });
  }

  _changeCurrentAdConf(targetIndex) {

    if (this.options.adConfList === false) {
      this.options.onError({errCode: -1, errMsg: "No advertising configuration"});
      return;
    }

    // console.log(this.options.adConfList);
    const strategy = this.options.adConfList.advert_strategy;
    
    if ((strategy.length - 1) < targetIndex) {
      targetIndex = 0;
    }

    this.currentIndex = targetIndex;
    this.currenAdconf = strategy[targetIndex];
    this.adUnitId = this.currenAdconf.source_app_key;
    this.options.onAdConfChange({type: 0, data: this.currenAdconf});
  }

}
